package com.jdd.common.util.encryption;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RASUtil {

    /**
     * @param info 需要签名的数据
     * @return
     */
    public static String sign(String info) throws Exception {

        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(BASE64Helper.decryptBASE64(EncryptedString.prikey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
        // 用私钥对信息生成数字签名
        java.security.Signature signet = java.security.Signature
                .getInstance("MD5withRSA");
        signet.initSign(myprikey);
        signet.update(info.getBytes("UTF-8"));
        // 对信息的数字签名
        byte[] signed = signet.sign();
        return BASE64Helper.encryptBASE64(signed);

    }

    /**
     * @param sign 签名信息
     * @param info 原数据
     * @return
     */
    public static boolean verifySign(String sign, String info) throws Exception {
        X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(BASE64Helper.decryptBASE64(EncryptedString.pubkey));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(bobPubKeySpec);
        byte[] signed = BASE64Helper.decryptBASE64(sign);
        java.security.Signature signetcheck = java.security.Signature.getInstance("MD5withRSA");
        signetcheck.initVerify(pubKey);
        signetcheck.update(info.getBytes());
        if (signetcheck.verify(signed)) {
            return true;
        } else {
            return false;
        }


    }


}

